<template>
    <a-modal
        title="修改头像"
        :visible="visible"
        centered
        :width="750"
        :maskClosable="false"
        :destroyOnClose="true"
        :footer="null"
        @cancel="visible = false"
    >
        <div class="tp-box">
            <div class="container">
                <div class="imageBox img-container">
                    <img id="tailoringImg" alt />
                    <div class="spinner" style="display: none">Loading...</div>
                </div>
            </div>
            <div class="tp-btn-group">
                <div class="cropped docs-preview">
                    <div class="square previewImg"></div>
                </div>
                <div class="cropped-txt2">图片预览</div>
                <div class="new-contentarea tc">
                    <a-row>
                        <a-col :span="6">
                            <a-button type="default" @click="changeScale(1)">
                                <template #icon><PlusOutlined /></template>
                            </a-button>
                        </a-col>
                        <a-col :span="6">
                            <a-button type="default" @click="changeScale(-1)">
                                <template #icon><MinusOutlined /></template>
                            </a-button>
                        </a-col>
                        <a-col :span="6">
                            <a-button type="default" @click="rotateLeft">
                                <template #icon><UndoOutlined /></template>
                            </a-button>
                        </a-col>
                        <a-col :span="6">
                            <a-button type="default" @click="rotateRight">
                                <template #icon><RedoOutlined /></template>
                            </a-button>
                        </a-col>
                    </a-row>
                    <a-row :gutter="10">
                        <a-col>
                            <a-upload name="file" v-model:file-list="fileList" :customRequest="customRequest" :showUploadList="false">
                                <a-button type="primary">
                                    <!-- <template #icon><UploadOutlined /></template> -->
                                    上传图片
                                </a-button>
                            </a-upload>
                        </a-col>
                        <a-col>
                            <a-button type="primary" @click="uploadSave()" :loading="uploading">保存</a-button>
                        </a-col>
                        <a-col>
                            <a-button type="default" @click="visible = false">取消</a-button>
                        </a-col>
                    </a-row>
                </div>
            </div>
        </div>
    </a-modal>
</template>
<script lang='ts'>
import { defineComponent, reactive, toRefs, nextTick, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from '@/store'
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { message } from 'ant-design-vue'
import { uploadStream } from '@/utils/ossUploadService'

export default defineComponent({
    name: 'avatarCropper',
    components: {},
    props: {},
    emits: ['update:url'],
    setup(props, ctx) {
        const router = useRouter()
        const store = useStore()
        const state = reactive({
            fileList: [],
            uploading: false,
            visible: false,
            imgSrc: '',
            ready: false,
            cropper: '' as any
        })
        onMounted(() => {})
        function edit() {
            state.visible = true
            nextTick(() => {
                let img = document.getElementById('tailoringImg') as HTMLCanvasElement
                state.cropper = new Cropper(img, {
                    aspectRatio: 1 / 1,
                    dragMode: 'move',
                    preview: '.previewImg', // 预览视图
                    guides: false, // 裁剪框的虚线(九宫格)
                    autoCropArea: 1, // 0-1之间的数值，定义自动剪裁区域的大小，默认0.8
                    movable: true, // 是否允许移动剪裁框
                    zoomable: true, // 是否允许缩放图片大小
                    rotatable: true, // 是否允许旋转图片
                    cropBoxMovable: false, //是否允许拖动裁剪框
                    cropBoxResizable: false, //是否允许拖动 改变裁剪框大小
                    ready: (e) => {
                        state.ready = true
                    },
                    crop: (e) => {
                        // 输出结果数据裁剪图像。
                    }
                })
            })
        }
        /**上传 */
        function customRequest(v) {
            // 转化为base64
            // const reader = new FileReader()
            // reader.readAsDataURL(file)
            // reader.onload = () => {
            //     state.imgSrc = reader.result as string
            //     if (state.cropper) {
            //         state.cropper.replace(state.imgSrc)
            //     }
            // }
            //  转化为blob
            if (state.cropper) {
                state.cropper.replace(getObjectURL(v.file))
            }
        }
        /**blob */
        function getObjectURL(file) {
            var url = ''
            if ((window as any).createObjectURL != undefined) {
                // basic
                url = (window as any).createObjectURL(file)
            } else if (window.URL != undefined) {
                // mozilla(firefox)
                url = window.URL.createObjectURL(file)
            } else if (window.webkitURL != undefined) {
                // webkit or chrome
                url = window.webkitURL.createObjectURL(file)
            }
            return url
        }

        /**上传保存 */
        function uploadSave() {
            if (!state.ready) {
                message.warning('请先上传图片')
                return
            }
            state.uploading = true
            uploadStream(state.cropper.getCroppedCanvas().toDataURL('image/png'), (res) => {
                if (res.res.statusCode == '200') {
                    ctx.emit('update:url', res.url)
                    state.visible = false
                } else {
                    message.error('图片上传失败!')
                }
                state.uploading = false
            })
        }
        function changeScale(num) {
            num = num || 1
            state.ready && state.cropper.zoom(num)
        }
        function rotateLeft() {
            state.ready && state.cropper.rotate(-90)
        }
        function rotateRight() {
            state.ready && state.cropper.rotate(90)
        }
        return {
            ...toRefs(state),
            customRequest,
            uploadSave,
            changeScale,
            rotateLeft,
            rotateRight,
            edit
        }
    }
})
</script>


<style lang="scss" scoped>
/**上传头像模态框 begin**/
.tp-box {
    width: 100%;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
}
.tp-title {
    font-family: PingFangSC-Medium;
    color: #333333;
    letter-spacing: 0;
    text-align: center;
    line-height: 60px;
    margin-bottom: 2%;
}
.tp-point {
    font-family: PingFangSC-Regular;
    color: #606266;
    letter-spacing: 0;
    line-height: 60px;
    font-size: 16px;
}
.container {
    width: 400px;
    position: relative;
    font-family: 微软雅黑;
    margin: 0;
    font-size: 18px;
}
.container p {
    line-height: 12px;
    line-height: 0px;
    height: 0px;
    margin: 10px;
    color: #bbb;
}
.tp-btn-group .new-contentarea .ant-row {
    margin: 30px 0;
}
.action {
    width: 400px;
    height: 30px;
    margin: 10px 0;
}
.cropped {
    width: 200px;
    height: 200px;
    border: 1px solid #dcdfe6;
    background: #f6f6f6;
    padding: 4px;
    box-shadow: 0px 0px 12px #ddd;
    text-align: center;
    box-sizing: content-box;
}
.cropped-txt2 {
    width: 200px;
    height: 60px;
    font-family: PingFangSC-Regular;
    color: #606266;
    letter-spacing: 0;
    text-align: center;
    line-height: 60px;
}
.imageBox {
    position: relative;
    height: 400px;
    width: 400px;
    background: #fff;
    overflow: hidden;
    background-repeat: no-repeat;
    cursor: move;
    background: url('');
}
.imageBox .thumbBox {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 200px;
    height: 200px;
    margin-top: -100px;
    margin-left: -100px;
    box-sizing: border-box;
    border: 1px solid rgb(102, 102, 102);
    box-shadow: 0 0 0 1000px rgba(0, 0, 0, 0.5);
    background: none repeat scroll 0% 0% transparent;
}
.imageBox .spinner {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    text-align: center;
    line-height: 400px;
    background: rgba(0, 0, 0, 0.7);
}
.Btnsty_peyton {
    width: 66px;
    display: block;
    float: right;
    margin-bottom: 10px;
    height: 57px;
    line-height: 57px;
    color: #ffffff;
    margin: 0px 2px;
    background-color: #f38e81;
    border-radius: 3px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    -ms-border-radius: 3px;
    -o-border-radius: 3px;
    text-decoration: none;
    cursor: pointer;
    box-shadow: 0px 0px 5px #b0b0b0;
    border: 0px #fff solid;
}

.previewImg {
    width: 200px;
    height: 200px;
    overflow: hidden;
    border-radius: 50%;
    border: 1px dashed #666;
}

/**上传头像模态框 End**/
</style>

